var home = new Array();
home['Width'] = 564;
home['Height'] = 754;

var lampe = new Array();
lampe['Width'] = 24;
lampe['Height'] = 24;

var camera = new Array();
camera['Width'] = 24;
camera['Height'] = 24;

var prise = new Array();
prise['Width'] = 17;
prise['Height'] = 30;

var detecteur = new Array();
detecteur['Width'] = 22;
detecteur['Height'] = 27;

var typeEquipment = new Array();
typeEquipment[0] = "lampe";
typeEquipment[1] = "camera";
typeEquipment[2] = "prise";
typeEquipment[3] = "detecteur";

$(document).on("pagecreate", "#main-page", function () {
    $(document).on("swiperight", "#main-page", function(e) {
        // We check if there is no open panel on the page because otherwise
        // a swipe to close the left panel would also open the right panel (and v.v.).
        // We do this by checking the data that the framework stores on the page element (panel: open).
        if ($(".ui-page-active").jqmData("panel") !== "open") {
            if (e.type === "swiperight") {
                $("#left-panel").panel("open");
            }
        }
    });
});

window.addEventListener("orientationchange", function(){
    loadEquipments();
    generateEquipementIHMAddEquipement();
}, false);

$(document).bind("mobileinit", function(){
      $.mobile.defaultPageTransition = 'none';
      $.mobile.defaultDialogTransition = 'none';
      $.mobile.useFastClick = true;
      $.mobile.pushStateEnabled = false;
});

var prevSelection = "tab1";
$("#navbar ul li").click(function () {
    var newSelection = $(this).children("a").attr("data-tab-class");
    $("." + prevSelection).addClass("ui-screen-hidden");
    $("." + newSelection).removeClass("ui-screen-hidden");
    prevSelection = newSelection;
});

$.mobile.document.on("click", "#lampeChambre", function (evt) {
    $("#popupCloseRight").popup("open");
    evt.preventDefault();
});


var isFirstClick = false;
var sizeWidthHalf = lampe['Width'] / 2;
var sizeHeightHalf = lampe['Height'] / 2;

var draggable = document.getElementById('equipementDraggable');
draggable.addEventListener('touchstart', function(event) {
    if(type == typeEquipment[0]) {
        $('#equipement').css({"width": lampe['Width'],"height": lampe['Height']});
    }
    else if(type == typeEquipment[1]) {
        $('#equipement').css({"width": camera['Width'],"height": camera['Height']});
    }
    else if(type == typeEquipment[2]) {
        $('#equipement').css({"width": prise['Width'],"height": prise['Height']});
    }
    else if(type == typeEquipment[3]) {
        $('#equipement').css({"width": detecteur['Width'],"height": detecteur['Height']});
    }
    
}, false);


$(".liEvenement").swiperight(function(e) {
    alert(this.id);
});

var listEquipementsAddEquipement = new Array();
draggable.addEventListener('touchend', function(event) {
    
    var offset = $('#imgHome').offset();
    
    var widthHome = $('#imgHome').width();
    var heightHome = $('#imgHome').height();

    //Calcul la perte de la taille en pourcentage
    var diminutionWidth = (((widthHome - home['Width'])/ home['Width'])*100)*(-1);
    var diminutionHeight = (((heightHome - home['Height'])/home['Height'])*100)*(-1);

    //on multiplie la valeur initiale par le taux puis on divise par 100 pour avoir la taille de l'equipement
    if(type == typeEquipment[0]) {
        var widthEquipment = lampe['Width'] * (1 - (diminutionWidth / 100));
        var heightEquipment = lampe['Height'] * (1 - (diminutionHeight / 100));
    }
    else if(type == typeEquipment[1]) {
        var widthEquipment = camera['Width'] * (1 - (diminutionWidth / 100));
        var heightEquipment = camera['Height'] * (1 - (diminutionHeight / 100));
    }
    else if(type == typeEquipment[2]) {
        var widthEquipment = prise['Width'] * (1 - (diminutionWidth / 100));
        var heightEquipment = prise['Height'] * (1 - (diminutionHeight / 100));
    }
    else if(type == typeEquipment[3]) {
        var widthEquipment = detecteur['Width'] * (1 - (diminutionWidth / 100));
        var heightEquipment = detecteur['Height'] * (1 - (diminutionHeight / 100));
    }
    sizeWidthHalf = widthEquipment / 2 + 10;
    sizeHeightHalf = heightEquipment / 2 + 10;

    widthEquipment = String(widthEquipment) +"px";
    heightEquipment = String(heightEquipment)+"px";
    
    $('#equipement').css({"width": widthEquipment,"height": heightEquipment});
    var touch = event.targetTouches[0];

    var x = (touch.pageX - offset.left) * 100 / widthHome;
    var y = (touch.pageY - offset.top) * 100 / heightHome;
    if(idMovingEquipment == "") {
	    $("#coordX").val(x);
	    $("#coordY").val(y);
    }
    else {
    	$("#coordXEquipementMoveType"+type+"Id"+idMovingEquipment).val(x);
        $("#coordYEquipementMoveType"+type+"Id"+idMovingEquipment).val(y);
    }

    var xLeft = touch.pageX - sizeWidthHalf;
    var xRight = touch.pageX + sizeWidthHalf;
    var yTop = touch.pageY - sizeHeightHalf;
    var yBottom = touch.pageY + sizeHeightHalf;

    
    //Vérifie le placement par rapport aux autres équipements
    if(listEquipementsAddEquipement != "") {
        var b_badLocation = false;
        var blockingEquipment = "";
        for(var i = 0;i < listEquipementsAddEquipement.length;i++) {
            if((yBottom < listEquipementsAddEquipement[i][2]) || (yTop > listEquipementsAddEquipement[i][3]) || (xRight < listEquipementsAddEquipement[i][0]) || (xLeft > listEquipementsAddEquipement[i][1])) {
                //b_badLocation = false;
            }
            else {
            	b_badLocation = true;
                blockingEquipment = i;
                $('#helpBadLocationEquipment').popup( "open", { x: touch.pageX, y: touch.pageY + 50} );
            }

        }
        if(b_badLocation) {
            draggable.style.left = (listEquipementsAddEquipement[blockingEquipment][1] + 1) + 'px';
            draggable.style.top = (listEquipementsAddEquipement[blockingEquipment][3] + 1) + 'px';
        }
    }
    
}, false);


draggable.addEventListener('touchmove', function(event) {
    var touch = event.targetTouches[0];

    // Place element where the finger is
    draggable.style.left = touch.pageX-sizeWidthHalf + 'px';
    draggable.style.top = touch.pageY-sizeHeightHalf + 'px';
    event.preventDefault();
    
}, false);


var type = "";
$(document).on('pagecreate pageshow','#locationEquipment_page',function(e,data){      
    var equipement = $('#equipement');
    var equipementDraggable = $('#equipementDraggable');
    if(type != $('#selectEquipment').val() && idMovingEquipment == "") {
        type = $('#selectEquipment').val();
        equipementDraggable.css({"top":"60%"});
        equipementDraggable.css({"left":"50%"});
        equipement.css({"content":"url(img/"+type+".png)"});


        if(type == typeEquipment[0]) {
            equipement.css({"width": lampe['Width'],"height": lampe['Height']});
        }
        else if(type == typeEquipment[1]) {
            equipement.css({"width": camera['Width'],"height": camera['Height']});
        }
        else if(type == typeEquipment[2]) {
            equipement.css({"width": prise['Width'],"height": prise['Height']});
        }
        else if(type == typeEquipment[3]) {
            equipement.css({"width": detecteur['Width'],"height": detecteur['Height']});
        }
    }
});


$(document).on('pageshow','#main-page',function(e,data){      
    loadEquipments();
});

var idMovingEquipment = "";
function moveEquipement(e) {
    id = this.id;
    
    //Chaines qui permettent d'extraire les différentes valeurs necessaires
    var paramID = "Id";
    var paramType = "Type";
    
    //Récupère le type de l'équipement
    type = id.substring(id.lastIndexOf(paramType)+paramType.length,id.lastIndexOf(paramID)); 
    //Récupère l'id de l'équipement
    var idEquipement = id.substring(id.lastIndexOf(paramID)+paramID.length);
    
    idMovingEquipment = idEquipement;
    $.mobile.changePage("#locationEquipment_page");
    
}

$('#emplacement').on('singletap click',function(){   
    idMovingEquipment = "";
});


$(document).on('pageshow','#locationEquipment_page',function(e,data){    
    generateEquipementIHMAddEquipement();
});


/* change event handler */
function flipChanged(e) {
    var id = this.id;
    var state = this.value;   
    var paramID = "IdEquipement";
    var paramType = "Type";
    var paramCode = "Code";
    var type = id.substring(id.lastIndexOf(paramType)+paramType.length,id.lastIndexOf(paramID)); 
    var codeRadio = id.substring(id.lastIndexOf(paramCode)+paramCode.length); 
    id = id.substring(id.lastIndexOf(paramID)+paramID.length,id.lastIndexOf(paramCode)); 
    if((this.id).substring(0,4) == paramType) {
        $('#popupType'+type+paramID+id+paramCode+codeRadio).val(state).flipswitch('refresh');
    }
    else {
        $('#Type'+type+paramID+id+paramCode+codeRadio).val(state).flipswitch('refresh');
    }
    
    if (type == "camera") {
    	var idEquipement = "camera" + id;
    	doCheckCamStatus(idEquipement);
    }
    var data = {
        'action': 'changerEtat',
        'code_radio': codeRadio,
        'b_etat': state,
        'i_idEquipement': id,
        'type':type
    };
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: 'PUT',
        url: 'https://tacks.fr/application/action.php',       
        data: data,      
        dataType: 'json',
        success: function (data, status) {
            var equipement = $("#imgType"+type+"IdEquipement"+id);
            
            if(type == typeEquipment[0]) {
                if(state == "off") {
                    equipement.attr('src',"img/"+type+".png");
                }
                else {
                    equipement.attr('src',"img/"+type+"Allume.png");
                }
            }
            
            console.log(id + " has been changed! " + state);
        },
        error: function (jqXHR, xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });

}


function validateLocation() { 
    if(idMovingEquipment == "") {
        if($("#coordX").val() == "" && $("#coordY").val() == "") {
            alert("Aucun emplacement sélectionné");
        }
        else {
            $("#locationCheck").prop('checked', true).checkboxradio('refresh');
            $.mobile.changePage("#addEquipements_page");
        }
    }
    else {     
        saveChangesEquipment();
    }
}



function cancelLocation() {
    $('#imgHome').next('img').remove();
}



//Check if form is correct
function controlForm() {
    if($("#nameEquipment").val() != "") {
        if ($('#locationCheck').is(":checked") && $("#coordX").val() != "" && $("#coordY").val() != "") {
            //Si caméra ou détecteur ou si code radio différent de vide
            if(choixEquipmentSelect == typeEquipment[1] || choixEquipmentSelect == typeEquipment[3] || $("#codeRadio").val() != "") {
                var nameEquipement = $("#nameEquipment").val();
                var coordX = $("#coordX").val();
                var coordY = $("#coordY").val();
                var codeRadio = $("#codeRadio").val();
                var data = {
                    'action': 'addEquipment',
                    's_name': nameEquipement,
                    's_type': choixEquipmentSelect,
                    'i_coordX': coordX,
                    'i_coordY': coordY,
                    'i_codeRadio': codeRadio,

                    'i_idMembre' : idMembre,
                    'i_room': '1'
                };

                data = $(this).serialize() + "&" + $.param(data);
                $.ajax({
                    type: 'POST',
                    url: 'https://tacks.fr/application/action.php',       
                    data: data,      
                    dataType: 'json',
                    //timeout: 5000,
                    success: function(data, status) {
                        console.log(data);
                        console.log("Equipement ajoute avec succes");
                        
                        loadEquipments();
        


                        emptyFormAddEquipment(); 
                         //Remet par defaut le style de l'équipement a ajouter
                        $('#equipementDraggable').css('top','60%');
                        $('#equipementDraggable').css('left','50%');
                        $('#equipement').css('width',lampe['Width']);
                        $('#equipement').css('height',lampe['Height']);
                        loadEventsTenement();
                        $.mobile.changePage("#equipements_page");
                    },
                    error: function(data,xhr, desc, err) {
                        console.log(data);
                        console.log(xhr);
                        console.log("Details: " + desc + "\nError:" + err);
                    }
                });
            }
            else{
                alert("probleme code radio");
            }               
        }
        else {

            alert("Aucun emplacement pour cet équipement");
        }
    }
    else {
        alert("Il faut renseigner un nom pour cet équipement");
    }
}

function coupleOutlet() {
    var data = {
        "action": "coupleEquipment"
    };
    var codeRadio = "";
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: 'GET',
        url: 'https://tacks.fr/application/action.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        data: data,
        success: function(data, status){
            codeRadio = data['code_radio'];
            console.log(data['msg']);
            $('#codeRadio').val(codeRadio);
            $('#popupDialogCouple').popup( 'open' );
        },
        error: function(data,jqXHR,xhr, desc, err) {
            console.log(data);
            console.log(xhr);     
            console.log("Details: " + desc + "\nError:" + err);         
        }
    });
    return false;
}

function emptyFormAddEquipment() {
    //to empty form and variable 
    $("#locationCheck").prop('checked', false).checkboxradio('refresh');
    $("#nameEquipment").val('');
    $("#coordX").val('');
    $("#coordY").val('');
    $("#codeRadio").val('');
    $('#saveEquipment').toggle(); 
}

var idMembre = "";
var nbEvenementTotal = 0;
$(document).ready(function(){    
	document.getElementsByTagName('body')[0].style.display = '';
    $.mobile.buttonMarkup.hoverDelay;
    
    //Récupère l'id du membre connecté
    getIdDroitMembre();
    
    if(droitMembre == "readonly") {
        $('#btnAddEquipements').css('display','none');   
    }
    // Active camera will refresh every 1 seconds (solution intermediaire)
    /*var TIMEOUT = 1000;
    var refreshInterval = setInterval(function() {
    var random = Math.floor(Math.random() * Math.pow(2, 31));
    $('img#camera').attr('src', 'http://tacks.fr:81/camera?i=' + Math.random());
    }, TIMEOUT);   */



    //Event btn
    $("#cancelLocation").on("click singletap", cancelLocation);
    $("#verifValidateLocation").on("click singletap", validateLocation);
    $("#saveEquipment").on("singletap click", controlForm);
    $("#coupleOutlet").on("click singletap", coupleOutlet);
    $("#validateCouple").on("click singletap", function() {$('#saveEquipment').show();$('#popupDialogCouple').popup( 'close' );});
    $("#cancelAddEquipment").on("click singletap",emptyFormAddEquipment);
    $(".deleteEquipmentBtn").on("singletap click", deleteEquipment);   




    //Loading equipments
    loadEquipments();

    //Loading Rooms
    loadRooms();
    
    //Loading events
    //Logement
    loadEventsTenement();       

});

//######## Camera 1 script #########

var imageNr = 0; // Serial number of current image
var finished = new Array(); // References to img objects which have finished downloading
var paused = false;

function createImageLayer() {
  var img = new Image();
  img.style.position = "absolute";
  img.style.width = "100%";
  img.style.zIndex = -1;
  img.onload = imageOnload;
  img.onclick = imageOnclick;
  img.src = "http://tacks.fr:81/?action=snapshot&n=" + (++imageNr);
  var webcam = document.getElementById("webcam");
  webcam.insertBefore(img, webcam.firstChild);
}

// Two layers are always present (except at the very beginning), to avoid flicker
function imageOnload() {
  this.style.zIndex = imageNr; // Image finished, bring to front!
  while (1 < finished.length) {
    var del = finished.shift(); // Delete old image(s) from document
    del.parentNode.removeChild(del);
  }
  finished.push(this);
  if (!paused) createImageLayer();
}
function imageOnclick() { // Clicking on the image will pause the stream
  paused = !paused;
  if (!paused) createImageLayer();
}

//######## Camera 2 script #########

var imageNr2 = 0; // Serial number of current image
var finished2 = new Array(); // References to img objects which have finished downloading
var paused2 = false;

function createImageLayerCame2() {
  var img2 = new Image();
  img2.style.position = "absolute";
  img2.style.width = "100%";
  img2.style.zIndex = -1;
  img2.onload = imageOnload2;
  img2.onclick = imageOnclick2;
  img2.src = "http://tacks.fr:80/?action=snapshot&n=" + (++imageNr2);
  var webcamDeux = document.getElementById("webcamDeux");
  webcamDeux.insertBefore(img2, webcamDeux.firstChild);
}

//Two layers are always present (except at the very beginning), to avoid flicker
function imageOnload2() {
  this.style.zIndex = imageNr2; // Image finished, bring to front!
  while (1 < finished2.length) {
    var del = finished2.shift(); // Delete old image(s) from document
    del.parentNode.removeChild(del);
  }
  finished2.push(this);
  if (!paused2) createImageLayerCame2();
}

function imageOnclick2() { // Clicking on the image will pause the stream
	  paused2 = !paused2;
	  if (!paused2) createImageLayerCame2();
	}

//######## Camera 3 script #########

var imageNr3 = 0; // Serial number of current image
var finished3 = new Array(); // References to img objects which have finished downloading
var paused3 = false;

function createImageLayerCame3() {
  var img3 = new Image();
  img3.style.position = "absolute";
  img3.style.width = "100%";
  img3.style.zIndex = -1;
  img3.onload = imageOnload3;
  img3.onclick = imageOnclick3;
  img3.src = "http://tacks.fr:8080/?action=snapshot&n=" + (++imageNr3);
  var webcamTrois = document.getElementById("webcamTrois");
  webcamTrois.insertBefore(img3, webcamTrois.firstChild);
}

//Two layers are always present (except at the very beginning), to avoid flicker
function imageOnload3() {
  this.style.zIndex = imageNr3; // Image finished, bring to front!
  while (1 < finished3.length) {
    var del = finished3.shift(); // Delete old image(s) from document
    del.parentNode.removeChild(del);
  }
  finished3.push(this);
  if (!paused3) createImageLayerCame3();
}

function imageOnclick3() { // Clicking on the image will pause the stream
	  paused3 = !paused3;
	  if (!paused3) createImageLayerCame3();
	}

//Mise en cache IMG
$.html5Loader({
 
filesToLoad:    'js/html5loader/files.json', // this could be a JSON or simply a javascript object
    onBeforeLoad:       function () {},
    onComplete:         function () {},
    onElementLoaded:    function ( obj, elm) { },
    onUpdate:           function ( percentage ) {}
});

function convertTimestanpToDate(parTimestamp) {
	parTimestamp = parTimestamp * 1000;
    date = new Date(parseInt(parTimestamp));
    annee = date.getFullYear();
    mois = date.getMonth();
    a_mois = new Array('Janvier', 'F&eacute;vrier', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Ao&ucirc;t', 'Septembre', 'Octobre', 'Novembre', 'D&eacute;cembre');
    j = date.getDate();
    jour = date.getDay();
    a_jours = new Array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi');
    
    var dateConvert = a_jours[jour]+ " " + j + " " + a_mois[mois] + " " + annee;
    return dateConvert;
}

var dataEventTenementOld = "";
var nbEvenementTotalOld = 0;
function loadEventsTenement() {
    var outputLogement = $('#list_historique_logement');

    //outputLogement.empty();
    var data = {
        "action": "listeEvenementsLogement"
    };
    var evenementsLogement = "";
    var evenementsLogementAffichage = "";
    var nbEvenementLogement = 0;     
    var dateEvenementLogement = "";
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: 'GET',
        url: 'https://tacks.fr/application/action.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        data: data,
        crossDomain: true,
        success: function(datas, status){
            $.each(datas, function(i,item){
                if(dateEvenementLogement == "" || dateEvenementLogement == convertTimestanpToDate(item.DATE_EVENEMENT)) {                
                    dateEvenementLogement = convertTimestanpToDate(item.DATE_EVENEMENT);
                    if(item.prenom != "null") {
                        evenementsLogement += '<li class="liEvenement"><h2>'+item.prenom+'</h2>';

                    }
                    else {
                        evenementsLogement += '<li class="liEvenement"><h2>Maison</h2>';
                    }
                    evenementsLogement += '<p style="white-space:normal;">'+item.DESCRIPTION_EVENEMENT+'</p>'
                    + '<p class="ui-li-aside"><strong>'+item.HEURE_EVENEMENT+'</strong>'+item.PERIODE_EVENEMENT+'</p></li>';
                    nbEvenementLogement++;
                    nbEvenementTotal++;
                }
                else {
                    evenementsLogementAffichage += '<li data-role="list-divider">'+dateEvenementLogement+'<span class="ui-li-count">'+nbEvenementLogement+'</span></li>' + evenementsLogement;
                    nbEvenementLogement = 1;
                    nbEvenementTotal++;
                    //outputLogement.append(evenementsLogement);
                    evenementsLogement = "";
                    if(item.prenom != "null") {
                        evenementsLogement =
                        '<li class="liEvenement"><h2>'+item.prenom+'</h2>'
                        + '<p style="white-space:normal;">'+item.DESCRIPTION_EVENEMENT+'</p>'
                        + '<p class="ui-li-aside"><strong>'+item.HEURE_EVENEMENT+'</strong>'+item.PERIODE_EVENEMENT+'</p></li>';
                        dateEvenementLogement = convertTimestanpToDate(item.DATE_EVENEMENT);
                    }
                    else {
                        evenementsLogement =
                        '<li><h2>Maison</h2>'
                        + '<p style="white-space:normal;">'+item.DESCRIPTION_EVENEMENT+'</p>'
                        + '<p class="ui-li-aside"><strong>'+item.HEURE_EVENEMENT+'</strong>'+item.PERIODE_EVENEMENT+'</p></li>';
                        dateEvenementLogement = convertTimestanpToDate(item.DATE_EVENEMENT);
                    }
                }                 
            });
            if(datas != "") {
                nbEvenementTotalOld = nbEvenementTotal;
                evenementsLogementAffichage += '<li data-role="list-divider">'+dateEvenementLogement+'<span class="ui-li-count">'+nbEvenementLogement+'</span></li>' + evenementsLogement;
                if(evenementsLogementAffichage != dataEventTenementOld) {
                    dataEventTenementOld = evenementsLogementAffichage;
                    outputLogement.empty().append(evenementsLogementAffichage);
                    outputLogement.listview().listview("refresh");
                }
                else {
                    nbEvenementTotal = nbEvenementTotalOld;
                }
            }
            else {
                outputLogement.empty();
                outputLogement.append('<li>Aucun évènement logement</li>');      
            }      
            loadEvenementsReglage();
                
        },
        error: function(){
            //outputLogement.text('Problème chargement des données.');

        }
    });
}

var dataEventReglageOld = "";
function loadEvenementsReglage() {
    //Reglage   
    outputReglage = $('#list_historique_reglage');

    //outputReglage.empty();
    data2 = {
        "action": "listeEvenementsReglage"
    };
    var evenementsReglage = "";
    var evenementsReglageAffichage = "";
    var nbEvenementReglage = 0;
    var dateEvenementReglage = "";
    data2 = $(this).serialize() + "&" + $.param(data2);
    $.ajax({
        type: 'GET',
        url: 'https://tacks.fr/application/action.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        data: data2,
        crossDomain: true,
        success: function(dataReglage, status){
            
            $.each(dataReglage, function(i,item){             
                if(dateEvenementReglage == "" || dateEvenementReglage == convertTimestanpToDate(item.DATE_EVENEMENT)) {
                    dateEvenementReglage = convertTimestanpToDate(item.DATE_EVENEMENT);
                    if(item.prenom != "null") {
                       evenementsReglage += '<li><h2>'+item.prenom+'</h2>';
                    }
                    else {
                        evenementsReglage += '<li><h2>Maison</h2>';
                    }
                    evenementsReglage += '<p style="white-space:normal;">'+item.DESCRIPTION_EVENEMENT+'</p>'
                    + '<p class="ui-li-aside"><strong>'+item.HEURE_EVENEMENT+'</strong>'+item.PERIODE_EVENEMENT+'</p></li>';
                    nbEvenementReglage++;
                    nbEvenementTotal++;
                }
                else {
                    
                    evenementsReglageAffichage += '<li data-role="list-divider">'+dateEvenementReglage+'<span class="ui-li-count">'+nbEvenementReglage+'</span></li>' + evenementsReglage 
                    nbEvenementReglage = 1;
                    nbEvenementTotal++;
                    //outputReglage.append(evenementsReglage);
                    evenementsReglage = "";
                    if(item.prenom != "null") {
                        evenementsReglage =
                        '<li><h2>'+item.prenom+'</h2>'
                        + '<p style="white-space:normal;">'+item.DESCRIPTION_EVENEMENT+'</p>'
                        + '<p class="ui-li-aside"><strong>'+item.HEURE_EVENEMENT+'</strong>'+item.PERIODE_EVENEMENT+'</p></li>';
                    }
                    else {
                        evenementsReglage =
                        '<li><h2>Maison</h2>'
                        + '<p style="white-space:normal;">'+item.DESCRIPTION_EVENEMENT+'</p>'
                        + '<p class="ui-li-aside"><strong>'+item.HEURE_EVENEMENT+'</strong>'+item.PERIODE_EVENEMENT+'</p></li>';
                    }
                    dateEvenementReglage = convertTimestanpToDate(item.DATE_EVENEMENT);
                }                 
            });
            if(dataReglage != "") {
                nbEvenementTotalOld = nbEvenementTotal;
                evenementsReglageAffichage += '<li data-role="list-divider">'+dateEvenementReglage+'<span class="ui-li-count">'+nbEvenementReglage+'</span></li>' + evenementsReglage;
                if(evenementsReglageAffichage != dataEventReglageOld) {
                    dataEventReglageOld = evenementsReglageAffichage;
                    outputReglage.empty().append(evenementsReglageAffichage).trigger("create");
                }
                else {
                    nbEvenementTotal = nbEvenementTotalOld;
                }
            }
            else {
                    outputReglage.empty().append('<li>Aucun évènement réglage</li>');   
            }
            outputReglage.listview().listview("refresh");

            
            loadNbEvenementTotal();
            
        },
        error: function(){
            //outputReglage.text('Problème chargement des données.');
        }
            
    }); 
    return false;
}
//Affiche le nombre d'evenement dans le menu
function loadNbEvenementTotal() {
    $('#nbEvenement').empty().append(nbEvenementTotal);
    nbEvenementTotal = 0;
}


function callbackError(button) {
    if (button == 2) {
        dataRequest();
    }
}

var choixEquipmentSelect = "lampe";


/* change event handler */
function selectEquipmentChanged(e) {
    if(choixEquipmentSelect != this.value) {
        $("#coordX").val('');
        $("#coordY").val('');
        choixEquipmentSelect = this.value;
         $("#codeRadio").val("");
        $("#locationCheck").prop('checked', false).checkboxradio('refresh');
    }

    //Si caméra ou detecteur
    if(choixEquipmentSelect == typeEquipment[1] || choixEquipmentSelect == typeEquipment[3]) {
        $('#coupleOutlet').css('display','none');
        $('#helpCoupleOutlet').css('display','none');
        $('#saveEquipment').css('display','inline');
    }
    else {
        $('#coupleOutlet').css('display','inline');
        $('#helpCoupleOutlet').css('display','');
        $('#saveEquipment').css('display','none');
    }
}

$("#selectEquipment").on("change", selectEquipmentChanged);

var idEquipment = "";
function deleteEquipment(e) {
    
    if(idEquipment != "") {
        var data = {
            action : "deleteEquipment",
            i_idEquipment : idEquipment,
            i_idMembre : idMembre
        };

        $.ajax({
            type: 'DELETE',
            url: 'https://tacks.fr/application/action.php',       
            data: data,      
            dataType: 'json',
            success: function(data, status) {
            	if(data != -1) {
                    console.log(data);
                    nomEquipement = data['nameEquipement'];
                    console.log(idEquipment + " has been deleted!");
                    loadEquipments();
                    //addEvent("a supprimé un équipement ("+nomEquipement+")");
                    loadEventsTenement();
                    $('#popupDialogDelete').popup('close');
                }
                else {
                    console.log(data);
                    console.log("idEquipement est vide");  
                }
            },
            error: function(jqXHR,xhr, desc, err) {
                console.log(xhr);     
                console.log("Details: " + desc + "\nError:" + err);         
            },
            complete: function(data) {
                 idEquipment = "";
            }

        });
    }
    else {
        console.warn("Problème... : id equipement est vide");   
    }
    return false;
}


function saveIdEquipment () {
    idEquipment = this.id;
}

//Loading equipments
var dataEquipementOld = "";
function loadEquipments(e){
        
        var output = $('#listeEquipement');
        //output.empty();
        var data = {
            "action": "listeEquipements"
        };
        var equipements = "";
        var b_titre = true;
        data = $(this).serialize() + "&" + $.param(data);
        $.ajax({
            type: 'GET',
            url: 'https://tacks.fr/application/action.php',
            dataType: 'jsonp',
            jsonp: 'jsoncallback',
            timeout: 5000,
            data: data,
            crossDomain: true,
            success: function(data, status){
                if(data['status'] == 0 || data['status'] == 2) {                  
                    console.log(data['msg']);
                    $.each(data['equipements'], function(i,item){

                        if(b_titre)equipements = '<tr><th class="label">Nom équipement</th><th class="label">État</th><th class="label"></th><th class="label"></th></tr>';    




                        if(item.TYPE_EQUIPEMENT != typeEquipment[3] && item.TYPE_EQUIPEMENT != typeEquipment[1]) {
                            equipements += '<tr><td>'+item.NOM_EQUIPEMENT+'</td>';
                            if(item.TYPE_EQUIPEMENT == typeEquipment[0]) {
                                var codeRadio = item.CODE_RADIO_LAMPE;
                            }
                            else if(item.TYPE_EQUIPEMENT == typeEquipment[2]) {
                                var codeRadio = item.CODE_RADIO_PRISE;
                            }
                            equipements += '<td><select class="flipEtatEquipement" name="Type'+item.TYPE_EQUIPEMENT+'IdEquipement'+item.ID_EQUIPEMENT+'Code'+codeRadio+'" id="Type'+item.TYPE_EQUIPEMENT+'IdEquipement'+item.ID_EQUIPEMENT+'Code'+codeRadio+'" data-role="flipswitch" data-theme="b" data-mini="true">';

                            var etatEquipement = "";
                            if(item.TYPE_EQUIPEMENT == typeEquipment[0]) {
                                etatEquipement = item.ETAT_LAMPE;
                            }
                            else if(item.TYPE_EQUIPEMENT == typeEquipment[1]) {
                                etatEquipement = item.ETAT_CAMERA;
                            }
                            else if(item.TYPE_EQUIPEMENT == typeEquipment[2]) {
                                etatEquipement = item.ETAT_PRISE;
                            }
                            if(etatEquipement == "off") {
                                equipements += '<option value="off" selected="selected">Off</option><option value="on">On</option>';
                            }
                            else {
                                equipements += '<option value="off">Off</option><option value="on" selected="selected">On</option>';
                            }
                            equipements += '</select></td>';
                        }
                        else {
                            equipements += '<tr><td colspan="2">'+item.NOM_EQUIPEMENT+'</td>';  
                        }
                        if(item.TYPE_EQUIPEMENT == typeEquipment[1]) {
                            if(droitMembre == "readonly") {
                                equipements += '<td></td><td></td></tr>';                        
                            }
                            else {
                                equipements += '<td><a id="reglage'+item.ID_EQUIPEMENT+'" href="#popupSetting'+item.TYPE_EQUIPEMENT+item.ID_EQUIPEMENT+'" data-rel="popup" data-position-to="window" class="requestCouple ui-btn ui-shadow ui-corner-all ui-icon-gear ui-btn-icon-notext">Réglages</a></td><td></td></tr>';                        

                            }
                        }
                        else {             
                            if(droitMembre == "readonly") {
                                equipements += '<td></td><td></td></tr>';         
                            }
                            else {
                                equipements += '<td><a id="reglage'+item.ID_EQUIPEMENT+'" href="#popupSetting'+item.TYPE_EQUIPEMENT+item.ID_EQUIPEMENT+'" data-rel="popup" data-position-to="window" class="requestCouple ui-btn ui-shadow ui-corner-all ui-icon-gear ui-btn-icon-notext">Réglages</a></td><td><a id="'+item.ID_EQUIPEMENT+'" href="#popupDialogDelete" data-rel="popup" data-position-to="window" class="requestDelete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-notext">Delete</a></td></tr>';                        
                            }
                        }
                        b_titre = false;



                    });
                    if(equipements != dataEquipementOld) {
                        dataEquipementOld = equipements;
                        output.empty().append(equipements);
                        output.trigger("create");
                    }
                    //$('.flipEtatEquipement').on('change',flipChanged);
                    //add event to delete equipment

                    $(".requestDelete").on("singletap click", saveIdEquipment);

                    console.log(data);
                }
                else if(data['status'] == 3) {
                    equipements = "<tr><td>Aucun équipement</td></tr>";
                    dataEquipementOld = equipements;
                    output.empty().append(equipements);
                    console.log(data['msg']);   
                }
                else {
                    //generateEquipementIHM(data['equipements']);
                    console.log(data['equipements']);
                    console.log(data['msg']);
                }

                generateEquipementIHM(data['equipements']);
                
            },
            error: function(){
                //output.text('Problème chargement des données.');
            }
    }); 
    return false;
};


//Loading rooms
var dataRoomsOld = "";
function loadRooms(e){
    var output = $('#listePieces');



    var data = {
        "action": "getPieces"
    };
    var pieces = "";
    var b_titre = true;
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: 'GET',
        url: 'https://tacks.fr/application/action.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        data: data,
        crossDomain: true,
        success: function(data, status){
            if(data['status'] == 0) {
                console.log(data['msg']);
                console.log(data['pieces']);

                pieces = "";
                $.each(data['pieces'], function(i,item){       
                    if(b_titre)pieces = '<tr><th class="label" style="width : 100%;">Nom pièce</th><th class="label">Température</th></tr>';
                    pieces += '<tr><td>'+item.NOM_PIECE+'</td>';

                    if(item.VALEUR_TEMP == 0 && item.DATE == 0) {
                        pieces += '<td>N/D</td>';
                    }
                    else {
                        if(item.VALEUR_TEMP > 20) {
                            pieces += '<td>'+(Math.round(item.VALEUR_TEMP*10)/10)+'°C <img src="img/thermoChaud.png" alt="thermometre rouge" style="width : 17px;height: 38px;"></td>';
                        }
                        else {
                            pieces += '<td>'+(Math.round(item.VALEUR_TEMP*10)/10)+'°C <img src="img/thermoFroid.png" alt="thermometre rouge" style="width : 17px;height: 38px;"></td>';
                        }
                    }
                                
                    b_titre = false;

                });
                if(pieces != dataRoomsOld) {
                    dataRoomsOld = pieces;
                    output.empty().append(pieces);
                    output.trigger("create");
                }

                console.log(data);
            }
            else if(data['status'] == 1) {
                pieces = "<tr><td>Aucune pièce enregistrée</td></tr>";
                if(pieces != dataRoomsOld) {
                    dataRoomsOld = pieces;
                    output.empty().append(pieces);
                }
                console.log(data['msg']);   
            }
            
        },
        error: function(){
            output.text('Problème chargement des données.');
        }
    }); 
    return false;
}



$("#btn_piece, #btn_equipements").on("click singletap", function() {
    if($(this).attr('id') == "btn_piece") {
        $("#equipements-table").css({"display": "none"});
        $("#pieces-table").css({"display": ""});
        $(this).html("Equipements");
        $(this).prop('id', 'btn_equipements');
        $("#btnAddEquipements").css({"display": "none"});
        
    }
    else {
        $("#pieces-table").css({"display": "none"});
        $("#equipements-table").css({"display": ""});
        $(this).html("Pièces");
        $(this).prop('id', 'btn_piece');
        // Sergio Merge r25
        $("#btnAddEquipements").css({"display": "block"});
    }
});


function saveChangesEquipment() {
    //Récupère l'id et le type
    id = this.id;
    var paramID = "Id";
    var paramType = "Type";
    var type = id.substring(id.lastIndexOf(paramType)+paramType.length,id.lastIndexOf(paramID)); 
    var idEquipement = id.substring(id.lastIndexOf(paramID)+paramID.length); 
    

    if(idMovingEquipment == "") {
        var nameEquipement = $('#nameEquipementType'+type+'Id'+idEquipement).val();
        var temperatureAllumage = "";
        var heureAllumage = "";
        var heureExtinction = "";
        var securite = "";
        //Si lampe ou prise
        if(type == typeEquipment[0] || type == typeEquipment[2]) {
        	if(!$('#activateHeureType'+type+'Id'+idEquipement).is(':checked')) {
                heureAllumage = "";
            }

            else {
                heureAllumage = $('#heureAllumageType'+type+'Id'+idEquipement).val();
            }

            
            if(!$('#desactivateHeureType'+type+'Id'+idEquipement).is(':checked')) {
                heureExtinction = "";
            }
            else {
                heureExtinction = $('#heureExtinctionType'+type+'Id'+idEquipement).val();
            }
        }
        //Si prise
        if(type == typeEquipment[2]) {
            
            if(!$('#activateTemperatureType'+type+'Id'+idEquipement).is(':checked')) {
                temperatureAllumage = 1000;
            }
            else {
                temperatureAllumage = $('#temperatureAllumageType'+type+'Id'+idEquipement).val();
            }
        }
        //Si detecteur
        if(type == typeEquipment[3]) {
            if($('#activateSecuriteType'+type+'Id'+idEquipement).is(':checked')) {
                var securite = 1;   
            }
            else {
                var securite = 0; 
            }
        }
        
        if(type == typeEquipment[3]) {
            var data = {
                'action': 'saveChangesEquipment',
                'i_idEquipement': idEquipement,
                'securite': securite,
                's_nameEquipement': btoa(nameEquipement),
                's_type': type,
                'idMembre':idMembre            
            };
        }
        else {
            var data = {
                'action': 'saveChangesEquipment',
                'i_idEquipement': idEquipement,
                'idMembre':idMembre,
                's_type': type,
                's_nameEquipement': btoa(nameEquipement),
                's_heureAllumage': heureAllumage,
                's_heureExtinction': heureExtinction,
                'temperatureAllumage': temperatureAllumage
            };
        }
    }
    else {
        var coordX = $('#coordXEquipementMoveType'+type+'Id'+idEquipement).val();
        var coordY = $('#coordYEquipementMoveType'+type+'Id'+idEquipement).val();

        var data = {
            'action': 'saveMoveChangesEquipment',
            'i_idEquipement': idEquipement,
            'idMembre':idMembre,
            's_type': type,
            'i_coordX':coordX,
            'i_coordY':coordY
        };
    }

    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: 'PUT',

        url: 'https://tacks.fr/application/action.php',       
        data: data,      
        dataType: 'json',
        success: function (data, status) {
            //TODO Vérifier les données saisies si pas de différence, si heure bon format
            console.log(idEquipement + " has been changed! ");
            loadEquipments();
            loadEventsTenement();
            idMovingEquipment = "";
            $.mobile.changePage("#equipements_page");
        },
        error: function (jqXHR, xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    });
}

function checkboxReglageEquipement() {

    id = this.id;
    //Chaines qui permettent d'extraire les différentes valeurs necessaires
    var paramID = "Id";
    var paramType = "Type";
    
    //Récupère le type de l'équipement
    var type = id.substring(id.lastIndexOf(paramType)+paramType.length,id.lastIndexOf(paramID)); 
    //Récupère l'id de l'équipement
    var idEquipement = id.substring(id.lastIndexOf(paramID)+paramID.length); 
    //Permet de determiner quel réglage est activé
    var reglage = id.substring(0,id.indexOf(paramType));


    if($('#'+id).is(':checked')) {
        if(reglage == "activateHeure") {
            $('#heureAllumageType'+type+'Id'+idEquipement).textinput( "option", "disabled", false );
        }
        else if(reglage == "desactivateHeure") {
            $('#heureExtinctionType'+type+'Id'+idEquipement).textinput( "option", "disabled", false );
        }
        else if(reglage == "activateTemperature") {
            $('#temperatureAllumageType'+type+'Id'+idEquipement).textinput( "option", "disabled", false );
            $('#temperatureAllumageType'+type+'Id'+idEquipement).slider( "option", "disabled", false );
            $('#choixActivateTemperatureType'+type+'Id'+idEquipement).checkboxradio( "enable" );
            $('#choixActivateTemperature2Type'+type+'Id'+idEquipement).checkboxradio( "enable" );
        } 
    }
    else {
        if(reglage == "activateHeure") {
            $('#heureAllumageType'+type+'Id'+idEquipement).textinput( "option", "disabled", true );
        }
        else if(reglage == "desactivateHeure") {
            $('#heureExtinctionType'+type+'Id'+idEquipement).textinput( "option", "disabled", true );
        }
        else if(reglage == "activateTemperature") {
            $('#temperatureAllumageType'+type+'Id'+idEquipement).textinput( "option", "disabled", true );
            $('#temperatureAllumageType'+type+'Id'+idEquipement).slider( "option", "disabled", true );
            $('#choixActivateTemperatureType'+type+'Id'+idEquipement).checkboxradio( "disable" );
            $('#choixActivateTemperature2Type'+type+'Id'+idEquipement).checkboxradio( "disable" );
        }
    }   
}

var offset = 0;
var widthHome = 0;
var heightHome = 0;
var equipements = "";
function generateEquipementIHM(listeEquipements) {
    
    $('div.view img').each( function(){
        if( $(this).attr("id") != "img_ID" ) {
            $(this).remove();
        }
    } );
    equipements = listeEquipements;
    console.log("genereate ihm :"+equipements);
    //picture equipments
    var outputImg = $('#img_ID');
       
    //Popup to change equipements state
    //var outputPopupState = $('#divPopupState');



    //Page Settings for each equipements 
    var outputSettingsEquipments = $('#popupReglage');
    

    var popup = "";
    
    var imgEquipment = "";
    
    //Attribut equipment
    var idEquipment = "";
    var nameEquipment = "";
    var type = "";
    var coordX = "";
    var coordY = "";
    var etat = "";
    
    //Size picture main
    //ATTENTION ENLEVER SI EFFET DE BORD - TEST POUR PASSAGE DE PORTRAIT A PAYSAGE
    //if(widthHome == 0 && heightHome == 0 && offset == 0 || offset != $('#img_ID').offset()) {
        offset = $('#img_ID').offset();
        widthHome = $('#img_ID').width();
        heightHome = $('#img_ID').height();
    //}
 
    
    //Calcul la perte de la taille en pourcentage
    var diminutionWidth = (((widthHome - home['Width'])/ home['Width'])*100)*(-1);
    var diminutionHeight = (((heightHome - home['Height'])/home['Height'])*100)*(-1);
    

    var widthEquipment = 0;
    var heightEquipment = 0;
       

    if (typeof equipements != "undefined" && equipements.length > 0) {
        $.each(equipements, function(i,item){

            console.log(item);
            //Recovers data
            idEquipment = item.ID_EQUIPEMENT;
            nameEquipment = item.NOM_EQUIPEMENT;
            type = item.TYPE_EQUIPEMENT;
            coordX = item.COORD_X;
            coordY = item.COORD_Y;
            if(type == typeEquipment[0]) {
                code_radio = item.CODE_RADIO_LAMPE;
                heureAllumage = item.HEURE_ALLUMAGE_LAMPE;
                heureExtinction = item.HEURE_EXTINCTION_LAMPE;
                etat = item.ETAT_LAMPE;
            }
            else if(type == typeEquipment[1]) {
                heureAllumage = item.HEURE_ALLUMAGE_CAMERA;
                heureExtinction = item.HEURE_EXTINCTION_CAMERA;
                etat = item.ETAT_CAMERA;      
            }
            else if(type == typeEquipment[2]) {
                code_radio = item.CODE_RADIO_PRISE;
                heureAllumage = item.HEURE_ALLUMAGE_PRISE;
                heureExtinction = item.HEURE_EXTINCTION_PRISE;
                etat = item.ETAT_PRISE;  
                temperatureAllumage = item.TEMPERATURE;

                is_superieur = item.IS_SUPERIEUR;
            }
            else if(type == typeEquipment[3]) {
                securite = item.SECURITE;
            }
            
            widthEquipment = 0;
            heightEquipment = 0;       

            coordXImg = widthHome * coordX / 100;
            coordYImg = heightHome * coordY / 100;


            //on multiplie la valeur initiale par le taux puis on divise par 100 pour avoir la taille de l'equipement
            if(type == typeEquipment[0]) {
                widthEquipment = lampe['Width'] * (1 - (diminutionWidth / 100));
                heightEquipment = lampe['Height'] * (1 - (diminutionHeight / 100));   

            }
            else if(type == typeEquipment[1]) {
                widthEquipment = camera['Width'] * (1 - (diminutionWidth / 100));
                heightEquipment = camera['Height'] * (1 - (diminutionHeight / 100));  
            }
            else if(type == typeEquipment[2]) {
                widthEquipment = prise['Width'] * (1 - (diminutionWidth / 100));
                heightEquipment = prise['Height'] * (1 - (diminutionHeight / 100));  
            }
            else if(type == typeEquipment[3]) {
                widthEquipment = detecteur['Width'] * (1 - (diminutionWidth / 100));
                heightEquipment = detecteur['Height'] * (1 - (diminutionHeight / 100));  
            }

            //Recentre l'equipement 
            coordXImg = coordXImg - (widthEquipment/2);
            coordYImg = coordYImg - (heightEquipment/2);



            ////////////////////////////////////////////////////
            //*************//Création de l'image*************//
            //////////////////////////////////////////////////
            if(type == typeEquipment[0]) {
                if(etat == "off") {
                imgEquipment = "<img id='imgType"+type+ "IdEquipement" +idEquipment+"' src='img/"+type+".png' onclick='$( \"#"+type+idEquipment+"popupCloseRight\" ).popup( \"open\" );' width='"+widthEquipment+"px' height='"+heightEquipment+"px' alt='img_"+type+"' style='position : absolute;top : "+coordYImg+"px;left:"+coordXImg+"px;z-index : 2;cursor: pointer ;'/>";
                }
                else if(etat == "on") {
                    imgEquipment = "<img id='imgType"+type+ "IdEquipement" +idEquipment+"' src='img/"+type+"Allume.png' onclick='$( \"#"+type+idEquipment+"popupCloseRight\" ).popup( \"open\" );' width='"+widthEquipment+"px' height='"+heightEquipment+"px' alt='img_"+type+"' style='position : absolute;top : "+coordYImg+"px;left:"+coordXImg+"px;z-index : 2;cursor: pointer ;'/>";
                }
            }

            else if(type == typeEquipment[1]) {
                imgEquipment = "<img id='imgType"+type+ "IdEquipement" +idEquipment+"' src='img/"+type+".png' width='"+widthEquipment+"px' height='"+heightEquipment+"px' alt='img_"+type+"' style='position : absolute;top : "+coordYImg+"px;left:"+coordXImg+"px;z-index : 2;' />";
            }
            else if(type == typeEquipment[2]) {
                imgEquipment = "<img id='imgType"+type+ "IdEquipement" +idEquipment+"' src='img/"+type+".png' onclick='$( \"#"+type+idEquipment+"popupCloseRight\" ).popup( \"open\" );' width='"+widthEquipment+"px' height='"+heightEquipment+"px' alt='img_"+type+"' style='position : absolute;top : "+coordYImg+"px;left:"+coordXImg+"px;z-index : 2;cursor: pointer ;'/>";
            }
            else if(type == typeEquipment[3]) {
                imgEquipment = "<img id='imgType"+type+ "IdEquipement" +idEquipment+"' src='img/"+type+".png' width='"+widthEquipment+"px' height='"+heightEquipment+"px' alt='img_"+type+"' style='position : absolute;top : "+coordYImg+"px;left:"+coordXImg+"px;z-index : 2;cursor: pointer ;'/>";
            }

            ////////////////////////////////////////////////////
            //****Création de la popup pour changer l'état***//
            //////////////////////////////////////////////////

            if(type == typeEquipment[0] || type == typeEquipment[2]) {
                popup = "";
                popup = '<div data-role="popup" id="'+type+idEquipment+'popupCloseRight" class="ui-content" style="max-width:450px" data-position-to="origin">';
                popup += '<a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn-a ui-icon-delete ui-btn-icon-notext ui-btn-right">Fermer</a>';
                popup += '<label for="popupType'+type+'IdEquipement'+idEquipment+'Code'+code_radio+'">Etat '+nameEquipment+':</label>';
                popup += '<select class="flipEtatEquipement" name="popupType'+type+'IdEquipement'+idEquipment+'Code'+code_radio+'" id="popupType'+type+'IdEquipement'+idEquipment+'Code'+code_radio+'" data-role="flipswitch">';
                if(etat == "off") {
                    popup += '<option value="off" selected="selected">Off</option><option value="on">On</option></select></div>';
                }
                else {
                    popup += '<option value="off">Off</option><option value="on" selected="selected">On</option></select></div>';
                }
            }

            ////////////////////////////////////////////////////
            //******Création de la popup de réglage**********//
            //////////////////////////////////////////////////


            popupReglage = '<div style="z-index : -1" data-role="popup" id="popupSetting'+type+idEquipment+'" data-theme="a" class="ui-corner-all"><a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn-a ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a>';



            popupReglage += '<form><div style="padding:10px 20px;">';

            //Champs hidden pour les coordonnées 
            popupReglage += '<input type="hidden" id="coordXEquipementMoveType'+type+'Id'+idEquipment+'" name="coordXEquipementMoveType'+type+'Id'+idEquipment+'" value="'+coordX+'" ><input type="hidden" id="coordYEquipementMoveType'+type+'Id'+idEquipment+'" name="coordYEquipementMoveType'+type+'Id'+idEquipment+'" value="'+coordY+'" >';
            popupReglage += '<h3>'+nameEquipment+'</h3><label for="nameEquipementType'+type+'Id'+idEquipment+'">Nom</label><input name="nameEquipementType'+type+'Id'+idEquipment+'" id="nameEquipementType'+type+'Id'+idEquipment+'" value="'+nameEquipment+'" placeholder="Nom équipement" data-theme="a" type="text" required>';
            //Si équipement lampe ou prise
            if(type == typeEquipment[0] || type == typeEquipment[2]) { 




                //Heure allumage
                if(heureAllumage == "") {
                    popupReglage += '<input id="activateHeureType'+type+'Id'+idEquipment+'" data-mini="true" class="activateReglage" name="activateHeureType'+type+'Id'+idEquipment+'" data-theme="a" type="checkbox">';
                    popupReglage += '<label for="activateHeureType'+type+'Id'+idEquipment+'">Activer en fonction de l\'heure</label>';
                    popupReglage += '<input data-clear-btn="true" name="heureAllumageType'+type+'Id'+idEquipment+'" id="heureAllumageType'+type+'Id'+idEquipment+'" value="'+heureAllumage+'" type="time" disabled>';
                }
                else {
                    popupReglage += '<input id="activateHeureType'+type+'Id'+idEquipment+'" data-mini="true" class="activateReglage" name="activateHeureType'+type+'Id'+idEquipment+'" data-theme="a" type="checkbox" checked>';
                    popupReglage += '<label for="activateHeureType'+type+'Id'+idEquipment+'">Activer en fonction de l\'heure</label>';
                    popupReglage += '<input data-clear-btn="true" name="heureAllumageType'+type+'Id'+idEquipment+'" id="heureAllumageType'+type+'Id'+idEquipment+'" value="'+heureAllumage+'" type="time">';
                }


                //Heure extinction

                if(heureExtinction == "") {
                    popupReglage += '<input id="desactivateHeureType'+type+'Id'+idEquipment+'" data-mini="true" class="activateReglage" name="desactivateHeureType'+type+'Id'+idEquipment+'" data-theme="a" type="checkbox">';
                    popupReglage += '<label for="desactivateHeureType'+type+'Id'+idEquipment+'">Désactiver en fonction de l\'heure</label>';
                    popupReglage += '<input data-clear-btn="true" name="heureExtinctionType'+type+'Id'+idEquipment+'" id="heureExtinctionType'+type+'Id'+idEquipment+'" value="'+heureExtinction+'" type="time" disabled>';
                }
                else {
                    popupReglage += '<input id="desactivateHeureType'+type+'Id'+idEquipment+'" data-mini="true" class="activateReglage" name="desactivateHeureType'+type+'Id'+idEquipment+'" data-theme="a" type="checkbox" checked>';
                    popupReglage += '<label for="desactivateHeureType'+type+'Id'+idEquipment+'">Désactiver en fonction de l\'heure</label>';
                    popupReglage += '<input data-clear-btn="true" name="heureExtinctionType'+type+'Id'+idEquipment+'" id="heureExtinctionType'+type+'Id'+idEquipment+'" value="'+heureExtinction+'" type="time">';
                }


            }
            //Si équipement prise
            if(type == typeEquipment[2]) {
                //Temperature allumage
                
                
                
            	if(temperatureAllumage == 1000) {
                    popupReglage += '<input id="activateTemperatureType'+type+'Id'+idEquipment+'" data-mini="true" class="activateReglage" name="activateReglage" data-theme="a" type="checkbox">';
                    popupReglage += '<label for="activateTemperatureType'+type+'Id'+idEquipment+'">Activer en fonction de la temperature (en C°)</label>';
                    popupReglage += '<fieldset data-role="controlgroup">';
                    popupReglage += '<input name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked" type="radio" disabled><label for="radio-choice-1">Allumer quand température inférieur au seuil et éteindre quand la température est supérieur</label>';
                    popupReglage += '<input name="radio-choice-1" id="radio-choice-2" value="choice-2" type="radio" disabled><label for="radio-choice-2">Eteindre quand température inférieur au seuil et allumer quand la température est supérieur</label>';popupReglage += '</fieldset>';

                    popupReglage += '<input name="temperatureAllumageType'+type+'Id'+idEquipment+'" id="temperatureAllumageType'+type+'Id'+idEquipment+'" value="18" min="-20" max="45" data-mini="true" data-highlight="true" data-theme="b" data-track-theme="b" type="range" disabled>';
                }
                else {
                    popupReglage += '<input id="activateTemperatureType'+type+'Id'+idEquipment+'" data-mini="true" class="activateReglage" name="activateReglage" data-theme="a" type="checkbox" checked>';
                    popupReglage += '<label for="activateTemperatureType'+type+'Id'+idEquipment+'">Activer en fonction de la temperature (en C°)</label>';
                    popupReglage += '<fieldset data-role="controlgroup">';
                    popupReglage += '<input name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked" type="radio"><label for="radio-choice-1">Allumer quand température inférieur au seuil et éteindre quand la température est supérieur</label>';
                    popupReglage += '<input name="radio-choice-1" id="radio-choice-2" value="choice-2" type="radio"><label for="radio-choice-2">Eteindre quand température inférieur au seuil et allumer quand la température est supérieur</label>';
                    popupReglage += '</fieldset>';
                    popupReglage += '<input name="temperatureAllumageType'+type+'Id'+idEquipment+'" id="temperatureAllumageType'+type+'Id'+idEquipment+'" value="'+temperatureAllumage+'" min="-20" max="45" data-mini="true" data-highlight="true" data-theme="b" data-track-theme="b" type="range">';
                }



            }
            //Si équipement detecteur
            if(type == typeEquipment[3]) {
                if(securite == 1) {
                    popupReglage += '<input id="activateSecuriteType'+type+'Id'+idEquipment+'" data-mini="true" name="activateReglage" data-theme="a" type="checkbox" checked><label for="activateSecuriteType'+type+'Id'+idEquipment+'">Activer sécurité</label>';
                }
                else {
                    popupReglage += '<input id="activateSecuriteType'+type+'Id'+idEquipment+'" data-mini="true" name="activateReglage" data-theme="a" type="checkbox"><label for="activateSecuriteType'+type+'Id'+idEquipment+'">Activer sécurité</label>';
                }


            }
            
            popupReglage += '<a href="#" id="modifyEquipmentType'+type+'Id'+idEquipment+'" class="ui-btn ui-corner-all ui-shadow ui-btn-b ui-btn-icon-left ui-icon-check">Valider</a>';
            popupReglage += '<hr><a id="moveEquipementType'+type+'Id'+idEquipment+'" href="#" class="ui-btn ui-mini ui-corner-all ui-shadow ui-btn-a">Déplacer équipement</a></div></form></div>';

            //////////////////////
            //Add html elements//
            ////////////////////
            outputImg.after(imgEquipment);
            outputImg.after(popup);
            outputSettingsEquipments.append(popupReglage);

            
            $("#moveEquipementType"+type+"Id"+idEquipment).off();
            $("#moveEquipementType"+type+"Id"+idEquipment).on("singletap click", moveEquipement);

            $("#modifyEquipmentType"+type+"Id"+idEquipment).off();
            $("#modifyEquipmentType"+type+"Id"+idEquipment).on("singletap click", saveChangesEquipment);


        });


        $(".flipEtatEquipement").off();
        $(".flipEtatEquipement").on("change", flipChanged);


        $(".activateReglage").off();
        $(".activateReglage").on("change",checkboxReglageEquipement);

        //refresh GUI
        $('.view').trigger("create");
        outputImg.trigger("create");
        outputSettingsEquipments.trigger("create");

    }
}
var offsetAddEquipment = 0;
var widthHomeAddEquipment = 0;
var heightHomeAddEquipment = 0;
function generateEquipementIHMAddEquipement() {
    
    var cptEquipment = 0;
    listEquipementsAddEquipement.length = 0;

    //Suppression des anciens equipements
    $('div#divImgHome img').each( function(){
        if( $(this).attr("id") != "imgHome" ) {
            $(this).remove();
        }
    } );
    
    if (typeof equipements != "undefined" && equipements.length > 0) {
        //picture equipments
        var outputImgAddEquipment = $('#imgHome');

        var imgEquipmentAddEquipment = "";

        //Attribut equipment
        var idEquipment = "";
        var nameEquipment = "";
        var type = "";
        var coordX = "";
        var coordY = "";
        var etat = "";

        //Size picture main
        if(widthHomeAddEquipment == 0 && heightHomeAddEquipment == 0 && offsetAddEquipment == 0) {
            offsetAddEquipment = outputImgAddEquipment.offset();
            widthHomeAddEquipment = outputImgAddEquipment.width();
            heightHomeAddEquipment = outputImgAddEquipment.height();
        }


        //Calcul la perte de la taille en pourcentage
        var diminutionWidthAddEquipment = (((widthHomeAddEquipment - home['Width'])/ home['Width'])*100)*(-1);
        var diminutionHeightAddEquipment = (((heightHomeAddEquipment - home['Height'])/home['Height'])*100)*(-1);  

        var widthEquipmentAddEquipment = 0;
        var heightEquipmentAddEquipment = 0;


        $.each(equipements, function(i,item){
            console.log(item);
            //Recovers data
            idEquipment = item.ID_EQUIPEMENT;
            nameEquipment = item.NOM_EQUIPEMENT;
            type = item.TYPE_EQUIPEMENT;
            coordX = item.COORD_X;
            coordY = item.COORD_Y;
            if(type == typeEquipment[0]) {
                heureAllumage = item.HEURE_ALLUMAGE_LAMPE;
                heureExtinction = item.HEURE_EXTINCTION_LAMPE;
                etat = item.ETAT_LAMPE;
            }
            else if(type == typeEquipment[1]) {
                heureAllumage = item.HEURE_ALLUMAGE_CAMERA;
                heureExtinction = item.HEURE_EXTINCTION_CAMERA;
                etat = item.ETAT_CAMERA;      
            }
            else if(type == typeEquipment[2]) {
                heureAllumage = item.HEURE_ALLUMAGE_PRISE;
                heureExtinction = item.HEURE_EXTINCTION_PRISE;
                etat = item.ETAT_PRISE;  
                temperatureAllumage = item.TEMPERATURE;

                is_securite = item.IS_SECURITE;
            }


            widthEquipmentAddEquipment = 0;
            heightEquipmentAddEquipment = 0;

            coordXAddEquipment = widthHomeAddEquipment * coordX / 100;
            coordYAddEquipment = heightHomeAddEquipment * coordY / 100;

            //on multiplie la valeur initiale par le taux puis on divise par 100 pour avoir la taille de l'equipement
            if(type == typeEquipment[0]) {     
                widthEquipmentAddEquipment = lampe['Width'] * (1 - (diminutionWidthAddEquipment / 100));
                heightEquipmentAddEquipment = lampe['Height'] * (1 - (diminutionHeightAddEquipment / 100));
            }
            else if(type == typeEquipment[1]) {
                widthEquipmentAddEquipment = camera['Width'] * (1 - (diminutionWidthAddEquipment / 100));
                heightEquipmentAddEquipment = camera['Height'] * (1 - (diminutionHeightAddEquipment / 100));  
            }
            else if(type == typeEquipment[2]) {
                widthEquipmentAddEquipment = prise['Width'] * (1 - (diminutionWidthAddEquipment / 100));
                heightEquipmentAddEquipment = prise['Height'] * (1 - (diminutionHeightAddEquipment / 100));  
            }
            else if(type == typeEquipment[3]) {
                widthEquipmentAddEquipment = detecteur['Width'] * (1 - (diminutionWidthAddEquipment / 100));
                heightEquipmentAddEquipment = detecteur['Height'] * (1 - (diminutionHeightAddEquipment / 100));  
            }

            //Recentre l'equipement 
            coordXAddEquipment = coordXAddEquipment - (widthEquipmentAddEquipment/2) + offsetAddEquipment.left;
            coordYAddEquipment = coordYAddEquipment - (heightEquipmentAddEquipment/2) + offsetAddEquipment.top;

            if(idMovingEquipment == "" || idEquipment != idMovingEquipment) {
                var coordLeftAddEquipment = coordXAddEquipment;
                var coordRightAddEquipment = coordXAddEquipment + widthEquipmentAddEquipment;
                var coordTopAddEquipment = coordYAddEquipment;
                var coordBottomAddEquipment = coordYAddEquipment + heightEquipmentAddEquipment;

                //Remplissage tableau pour éviter le placement d'équipement par dessus d'autres
                listEquipementsAddEquipement[cptEquipment] = [coordLeftAddEquipment,coordRightAddEquipment,coordTopAddEquipment,coordBottomAddEquipment];


                //Cree l'image pour la partie add equipement
                imgEquipmentAddEquipment = "<img id='imgAddEquipmentType"+type+ "IdEquipement" +idEquipment+"' src='img/"+type+".png' width='"+widthEquipmentAddEquipment+"px' height='"+heightEquipmentAddEquipment+"px' alt='img_"+type+"' style='border : 1px red dashed;position : absolute;top : "+coordYAddEquipment+"px;left:"+coordXAddEquipment+"px;z-index : 2;'/>";

                //Add html elements
                outputImgAddEquipment.after(imgEquipmentAddEquipment);
                cptEquipment++;
            }
            else {
                //Déplacement équipement dans réglage
                equipement = $('#equipement');
                equipementDraggable = $('#equipementDraggable');
                equipementDraggable.css({"top":String(coordYAddEquipment)+"px"});
                equipementDraggable.css({"left":String(coordXAddEquipment)+"px"});
                equipement.css({"content":"url(img/"+type+".png)"});
                if(type == typeEquipment[0]) {
                    equipement.css({"width": lampe['Width'],"height": lampe['Height']});
                }
                else if(type == typeEquipment[1]) {
                    equipement.css({"width": camera['Width'],"height": camera['Height']});
                }
                else if(type == typeEquipment[2]) {
                    equipement.css({"width": prise['Width'],"height": prise['Height']});
                }
                else if(type == typeEquipment[3]) {
                    equipement.css({"width": detecteur['Width'],"height": detecteur['Height']});
                }
                
            }

            
        });
        if(idMovingEquipment != "") {
            $('#backLocationPage').attr('href','#equipements_page');   
        }
        else {
            $('#backLocationPage').attr('href','#addEquipements_page');   
        }
    
        //refresh GUI   
        outputImgAddEquipment.trigger("create");
    }
}


function updateGUI() {
    loadEquipments();
    loadEventsTenement();
    loadRooms();
}
//Use function updateGUI all the 30 seconds
setInterval(updateGUI,30000);


//CREATION D'UN NOUVEL UTILISATEUR

function getRadioVal(formId, name) {
	var radios;
	var val;
	$(document).ready(function(){
		var form = document.getElementById(formId);
	    // get list of radio buttons with specified name
	    radios = form.elements[name];
	});
    // loop through list of radio buttons
    for (var i=0, len=radios.length; i<len; i++) {
        if ( radios[i].checked ) { // radio checked?
            val = radios[i].value; // if so, hold its value in val
            break; // and break out of for loop
        }
    }
    return val; // return value of checked radio or undefined if none checked
}

function getIdDroitMembre() {
    idMembre = window.localStorage.getItem("id_membre");   
    droitMembre = window.localStorage.getItem("droit");  
}

$('#addUser').bind('click singletap',function(event){
	var nom = $('#nom').val();
	var prenom = $('#prenom').val();
	var emailA = $('#email').val();
	email = window.btoa(emailA);
	var tel = $('#tel').val();
	var login = $('#login').val();
	var password = $('#pwd').val();
	password = window.btoa(password);
	var pass_confirm = $('#pass_confirm').val();
	pass_confirm = window.btoa(pass_confirm);
	var droit = getRadioVal('createUserForm', 'droit');
	var idMembre = window.localStorage.getItem("id_membre");
	console.log(" B64 pwd = " + password + " conf: " + pass_confirm);
    var data = {
        "action": "addUser",
        "nom": nom,
        "prenom": prenom,
    	"email": email,
    	"tel": tel,
    	"droit": droit,
        "login": login,
        "password": password,
        "pass_confirm": pass_confirm,
        "id_membre": idMembre
    };
    if (!idMembre) {
    	console.log("Utilisateur non authentifié");
    	
    }else if (!nom || !prenom || !email || !tel || !login || !password || !pass_confirm || !droit) {
    	var msg = "Veuillez remplir les champs manquants.";
    	console.log(msg);
    	$("#alertAddUser").empty();
		document.getElementById("alertAddUser").innerHTML = msg;
    	console.log(msg);
    	
    }else if (password != pass_confirm){
    	var msg = "Vos mots de passe sont différents, veuillez recommencer.";
    	$("#alertAddUser").empty();
		document.getElementById("alertAddUser").innerHTML = msg;
    	console.log(msg);
    	
    }else {
	    data = $(this).serialize() + "&" + $.param(data);
	    $.ajax({
	        type: 'POST',
	        url: 'https://tacks.fr/application/action.php',
	        dataType: 'jsonp',
	        jsonp: 'jsoncallback',
	        timeout: 5000,
	        data: data,
	        crossDomain: true,
	        success: function(data, status){
	        	console.log('Creation new user');
	        	console.log(data);
	        	if (data['status'] == 0) {
	        		console.log(data['msg']);
	        		//TODO - Display error msg HTML
	        		//alert(data['msg']);
	        	}else if (data['status'] == 1) {
	        		console.log(data['msg']);
	        		alert(data['msg']);
	        	}else if (data['status'] == 2) {
	        		console.log(data['msg']);
	        		alert(data['msg']);
	        	}else if (data['status'] == 3) {
	        		console.log(data['msg']);
	        		alert(data['msg']);
	        	}
	        },
	        error: function(data,jqXHR,xhr, desc, err) {
	            console.log(data);
	            console.log(xhr);     
	            console.log("Details: " + desc + "\nError:" + err);  
	            console.warn('Connection failed');
	            location.reload(); 
	        }
	    });
    }
});


//FUNCTION GET FAMILLY USERS LIST 
function getUsersFamillyList() {
    $("#waitingUsersLoad").css({"display": "inline"});
	var userLoged = window.localStorage.getItem("login");
	var listUsersUL = "";
	var famillyUser = "";
	var nom = "";
	var prenom = "";
	var droit = "";
	var login = "";
	var obj = "";
	var data = {
     "action": "getFamillyUsers",
 };
 
 data = $(this).serialize() + "&" + $.param(data);
 $.ajax({
     type: 'GET',
     url: 'https://tacks.fr/application/action.php',
     dataType: 'jsonp',
     jsonp: 'jsoncallback',
     timeout: 5000,
     data: data,
     crossDomain: true,
     success: function(data, status){
     	console.log('Get fammily users');
     	console.log(data);
			
			var listUser = data['listUsers'];
			listUser = listUser.replace(/([^.a-z0-9A-Z:{}",-\[\]]+)/g, '');
			console.log(listUser);
			obj = JSON.parse(listUser);
			
			for (var i = 0; i < obj.length; i++) {
				login = obj[i].login;
				droit = obj[i].droit;
				if (userLoged != login && droit != "root" && droit !="0") {
					nom = obj[i].nom;
					prenom = obj[i].prenom;
					login = obj[i].login;
					var key = nom+prenom;

					if (droit == "readonly") {
						var droitHtml = '<td>'
					   				+		'<p><select name="" id="'+login+'" data-role="flipswitch" data-theme="b" data-mini="true" onchange="updateFamUserDroit(this.id)">'
						   			+				'<option value="readonly" selected="selected">RO</option><option value="readwrite">RW</option>'
						   			+		'</select></p>'
				   					+	'</td>'
					}else if (droit == "readwrite") {
						var droitHtml = '<td>'
					   				+		'<p><select name="" id="'+login+'" data-role="flipswitch" data-theme="b" data-mini="true" onchange="updateFamUserDroit(this.id)">'
						   			+				'<option  value="readonly">RO</option><option value="readwrite" selected="selected">RW</option>'
						   			+		'</select></p>'
				   					+	'</td>'
					}else if (droit == "superuser"){
						var droitHtml = '<td>'
					   				+		'<p> Super utilisateur</p>'
				   					+	'</td>'	
					}
					
					ListUserHead = '<tr><th class="label">Avatar</th><th class="label">Utilisateur</th><th class="label">Droit</th><th class="label">Action</th></tr>';
					listUsersUL += '<tr>'
				   				+	'<td>'
				   				+		'<img src="img/png_images/user_icon.png">'
				   				+	'</td>'
				   				+	'<td>' 
				   				+		'<p><b>'+ nom + ' '+ prenom +'</b><p>'
			   					+	'</td>'
				   				+	droitHtml
				   				+	'<td>'
				   				+		'<p><a href="#" id="'+ login +'" value="Supprimer utilisateur"class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-notext" onclick="deleteUserFromFamilly(this.id)">delete</a></p>'
			   					+	'</td>'
								+	'</tr>';
					$("#listFamillyUsers").empty();
					$("#listFamillyUsers").append(ListUserHead);
					$("#listFamillyUsers").append(listUsersUL);
					$("#listFamillyUsers").trigger("create");
					$("#waitingUsersLoad").css({"display": "none"});
				} 
			}	 
     },
     error: function(data,jqXHR,xhr, desc, err) {
         console.log(data);
         console.log(xhr);     
         console.log("Details: " + desc + "\nError:" + err);  
         console.warn('Connection failed');
         
         $("#listFamillyUsers").empty();
         listUsersUL = "<p>Un problème d'accès à votre serveur. </br> Veuillez recommencer ultérieurement. <p>";
		 $("#listFamillyUsers").append(listUsersUL);
		 $("#listFamillyUsers").trigger("create");
		 $("#waitingUsersLoad").css({"display": "none"});
     }
 });
}

// Restreindre la création d'un SUPER USER 
function isPermitDisplayInput() {
	var droit = window.localStorage.getItem("droit");
	if (droit != "root") {
		$("#superuser").css({"display": "none"});
		$("#superuserLabel").css({"display": "none"});
	}else {
		$("#superuser").css({"display": "inline"});
		$("#superuserLabel").css({"display": "inline"});
	}
}

// TODO - DELETE USER FROM Familly user list - PENDING GET USER PAGE DONE	
function deleteUserFromFamilly(login) {
	var idMembre = window.localStorage.getItem("id_membre");
    var data = {
        "action": "deleteUser",
        "login": login,
        "id_membre": idMembre
    };
	
	//Call pop confirm
     
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: 'GET',
        url: 'https://tacks.fr/application/action.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        data: data,
        crossDomain: true,
        success: function(data, status){
        	console.log('Delete user');
        	console.log(data);
        	if(data['status'] == 0) {
        		console.log(data['msg']);
        	}else if (data['status'] == 1){
        		console.log(data['msg']);
        		getUsersFamillyList();
        	}
        },
        error: function(data,jqXHR,xhr, desc, err) {
            console.log(data);
            console.log(xhr);     
            console.log("Details: " + desc + "\nError:" + err);  
            console.warn('Connection failed');
            getUsersFamillyList();
        }
    }); 
}



// UPDATE DROIT USER FROM Familly user list - PENDING GET USER PAGE DONE
//$('#updateFamUserDroit').bind('click singletap',function(event){
function updateFamUserDroit(login) {

	var droit = $('#'+login).val();
	var idMembre = window.localStorage.getItem("id_membre");
    var data = {
        "action": "updateUserDroit",
        "login": login,
        "droit": droit,
        "id_membre": idMembre
    };
  
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: 'GET',
        url: 'https://tacks.fr/application/action.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        data: data,
        crossDomain: true,
        success: function(data, status){
        	console.log('update User Droit');
        	console.log(data);
        },
        error: function(data,jqXHR,xhr, desc, err) {
            console.log(data);
            console.log(xhr);     
            console.log("Details: " + desc + "\nError:" + err);  
            console.warn('Connection failed');
        }
    }); 
}


//TODO - GET USER INFOS
$('#userPage').bind('click singletap',function(event){
	getUserInfo();
});

function getUserInfo() {
    $("#waitingUserInfoLoad").css({"display": "inline"});
	var login = window.localStorage.getItem("login");
	var outPutInfosUsers = $('#listInfosUser');
	var nom = "";
	var prenom = "";
	var email ="";
	var tel = "";

    var data = {
        "action": "getUserInfos",
        "login": login
    };
    
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: 'GET',
        url: 'https://tacks.fr/application/action.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        data: data,
        crossDomain: true,
        success: function(data, status){
        	console.log('Get user infos');
        	console.log(data);
        	if (data['status'] == 0) {
				alert(data['msg']);
				
        	}else if (data['status'] == 1) {
        		console.log(data['msg']);
        		console.log(data['msg']);
				
				var infosUser = data['infosUser'];
				infosUser = infosUser.replace(/([^.a-z0-9A-Z:{}",-\[\]]+)/g, '');
				console.log(infosUser);
				obj = JSON.parse(infosUser);
				
				nom = obj[0].nom;
				prenom = obj[0].prenom;
				email = obj[0].email;
				tel = obj[0].tel;

				console.log(obj[0].nom + " " + obj[0].prenom + " " + email + " "+ tel);
				var infosUserLI = '<li><a href="#" class="ui-btn ui-shadow ui-corner-all">' 
									+ '<img src="img/png_images/user_icon.png"><p><h2>' + nom + ' ' + prenom + '</h2></p></a></li>'
									+'<li><a href="#" id="infoMail" class="ui-btn ui-shadow ui-corner-all ui-btn-icon-left ui-icon-mail"><p>' + email + '</p></a></li>'
									+'<li><a href="#" id="infoTel" class="ui-btn ui-shadow ui-corner-all ui-btn-icon-left ui-icon-phone"><p>' + tel + '</p></a></li>' ;
				outPutInfosUsers.empty();
				outPutInfosUsers.append(infosUserLI);
				outPutInfosUsers.trigger("create");
			    $("#waitingUserInfoLoad").css({"display": "none"});
        	}

        },
        error: function(data,jqXHR,xhr, desc, err) {
            console.log(data);
            console.log(xhr);     
            console.log("Details: " + desc + "\nError:" + err);  
            console.warn('Access to server failed');
            
		    $("#waitingUserInfoLoad").css({"display": "none"});


        }
    });
}

//TODO - UPDATE USER INFOS - PENDING ADD BUTTON
$('#updateUserInfos').bind('click singletap',function(event){
	$("#updateInfosAlert").css({"display": "none"});
	var login = window.localStorage.getItem("login");
	var emailA = $('#emailUpdate').val();
	email = window.btoa(emailA);
	var tel = $('#telUpdate').val();
	var idMembre = window.localStorage.getItem("id_membre");
	
	console.log(email + " " + tel + " idMembre: " + idMembre + " login " + login );
    var data = {
        "action": "updateUserInfos",
        "login": login,
        "email": email,
        "tel": tel,
        "id_membre": idMembre
    };
    
    if(!email || !tel) {
    	$("#updateInfosAlert").css({"display": "inline"});
    	$("#updateInfosAlert").css({"color":"red"});
		var msg = "Veuillez compléter les champs vides.";
		document.getElementById("updateInfosAlert").innerHTML = msg;
		
    } else {

	    data = $(this).serialize() + "&" + $.param(data);
	    $.ajax({
	        type: 'GET',
	        url: 'https://tacks.fr/application/action.php',
	        dataType: 'jsonp',
	        jsonp: 'jsoncallback',
	        timeout: 5000,
	        data: data,
	        crossDomain: true,
	        success: function(data, status){
	        	console.log('update User infos');
	        	console.log(data);
	        	
	        	if(data['status'] == 1) {
	        		$("#preferencesPara").css({"display": "none"});
					$("#updateInfosAlert").css({"display": "inline"});
	 				$("#updateInfosAlert").css({"color": "blue"});
	        		var msg = "Vos préférences ont été mise à jour.";
					document.getElementById("updateInfosAlert").innerHTML = msg;
					getUserInfo();
	        	}else if (data['status'] == 0) {
	        		alert(data['msg']);
	        	}
	        },
	        error: function(data,jqXHR,xhr, desc, err) {
	            console.log(data);
	            console.log(xhr);
	            console.log("Details: " + desc + "\nError:" + err);  
	            console.warn('Connection failed');
            
            	$("#preferencesPara").css({"display": "none"});
 				$("#updateInfosAlert").css({"display": "inline"});
 				$("#updateInfosAlert").css({"color": "blue"});
         		var msg = "Vos préférences ont été mise à jour.";
 				document.getElementById("updateInfosAlert").innerHTML = msg; 
 				getUserInfo();
	        }
	    });
    }
});

// UPDATE USER PASSWORD 
$('#updateUserPassword').bind('click singletap',function(event){
	$("#updatePasswordAlert").css({"display": "none"});
	var login = window.localStorage.getItem("login");
	var password = $('#passwordUpdate').val();
	password = window.btoa(password);
	var pass_confirm = $('#pass_confirmUpdate').val();
	pass_confirm = window.btoa(pass_confirm);
	
	console.log(login+password+pass_confirm);
    var data = {
        "action": "updateUserPassword",
        "login": login,
        "password": password,
        "pass_confirm": pass_confirm
    };
    
    if(!password || !pass_confirm) {
    	$("#updatePasswordAlert").css({"display": "inline"});
    	$("#updatePasswordAlert").css({"color":"red"});
		var msg = "Veuillez compléter les champs vides.";
		document.getElementById("updatePasswordAlert").innerHTML = msg;
    
    } else if (password != pass_confirm) {
    	$("#updatePasswordAlert").css({"display": "inline"});
    	$("#updatePasswordAlert").css({"color":"red"});
		var msg = "Vos deux mots de passe sont différents. Veuillez recommencer.";
		document.getElementById("updatePasswordAlert").innerHTML = msg;
    } else {
    
	    data = $(this).serialize() + "&" + $.param(data);
	    $.ajax({
	        type: 'GET',
	        url: 'https://tacks.fr/application/action.php',
	        dataType: 'jsonp',
	        jsonp: 'jsoncallback',
	        timeout: 5000,
	        data: data,
	        crossDomain: true,
	        success: function(data, status){
	        	console.log('update User password');
	        	console.log(data);
	        	if (data['status'] == 0) {
	        		console.log(data['msg']);
	        		$("#updatePasswordAlert").empty();
	        		$("#updatePasswordAlert").css({"display": "inline"});
	        		var msg = "La mise à jour de votre mot de passe à échouée.";
					document.getElementById("updatePasswordAlert").innerHTML = msg;
	        		alert(data['msg']);
	        	}else if (data['status'] == 1) {
	        		console.log(data['msg']);
	        		$("#updatePasswordAlert").empty();
					$("#updatePasswordAlert").css({"display": "inline"});
					$("#updatePasswordAlert").css({"color": "blue"});
	        		var msg = "Votre mot de passe a été correctement mise à jour.";
					document.getElementById("updatePasswordAlert").innerHTML = msg;
	        	}
	        },
	        error: function(data,jqXHR,xhr, desc, err) {
	            console.log(data);
	            console.log(xhr);     
	            console.log("Details: " + desc + "\nError:" + err);  
	            console.warn('Connection failed');
	            
	            $("#updatePasswordAlert").css({"display": "inline"});
	        	$("#updatePasswordAlert").css({"color":"red"});
	    		var msg = "Problème d'accès au serveur.";
	    		document.getElementById("updatePasswordAlert").innerHTML = msg;
	        }
	    });
    }
});


$('#updateUserInfosPwdURL').bind('click singletap',function(event){
	$("#paraFormPwd").css({"display": "inline"});
	$("#preferencesPara").css({"display": "inline"});
	$("#updatePasswordAlert").css({"display": "none"});
	$("#updateInfosAlert").css({"display": "none"});
	
	var email = $("#infoMail").text();
	var tel = $("#infoTel").text();
	console.log(email + " ", + tel);
	$("#emailUpdate").val(email);
	$("#telUpdate").val(tel);
});

// Send email from user to tacks team
$('#sendEmail').bind('click singletap',function(event){
	var userLogged =  window.localStorage.getItem("login");
	var idMembre =  window.localStorage.getItem("id_membre");
	var subject = $("#subjectEmail").val();
	subject = window.btoa(subject);
	var message = $("#msgEMail").val();
	message = window.btoa(message);
	
	console.log("sub: "+ subject + " msg: "+ message);
	
	var data = {
	        "action": "sendEmail",
	        "login": userLogged,
	        "subject": subject,
	        "message": message,
	        "id_membre": idMembre
	    };
	
	if(!subject && !message) {
		var msg = "Veuillez ajouter un sujet et un message avant d'envoyer."
		console.log(msg);
	} else {
	 
	    data = $(this).serialize() + "&" + $.param(data); 
	    $.ajax({
	        type: 'GET',
	        url: 'https://tacks.fr/application/action.php',
	        dataType: 'jsonp',
	        jsonp: 'jsoncallback',
	        timeout: 5000,
	        data: data,
	        cache: true,
	        crossDomain: true,
	        success: function(data, status){
	        	console.log('Apps user sendMail');
	        	if (data['status'] == 1){
	        		console.log(data['msg']);
	        	}
	        },
	        error: function(data,jqXHR,xhr, desc, err) {
	            console.log(data);
	            console.log(xhr);     
	            console.log("Details: " + desc + "\nError:" + err);  
	            console.warn('Connection failed');
	            location.reload(); 
	        }
	    }); 
	}
});


// FUNCTION ALLUMER/ETEINDRE LA CAMERA 1 et 2
function videoStreamOrStop(idCamera, action) {
	var userLogged =  window.localStorage.getItem("login");
	var idMembre =  window.localStorage.getItem("id_membre");
	//alert(idCamera + " " + action + " " + userLogged + " "+ idMembre);
    var data = {
        "action": action,
        "login": userLogged,
        "idMembre": idMembre,
        "id_camera": idCamera
    };
     
    data = $(this).serialize() + "&" + $.param(data); 
    $.ajax({
        type: 'GET',
        url: 'https://tacks.fr/application/action.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        data: data,
        crossDomain: true,
        success: function(data, status){
        	if (action =="videoStream") {
        		console.log('Video stream');
        	}else {
        		console.log('Video stop');
        	}
        	console.log(data);
        	if(data['status'] == 0) {
        		console.log(data['msg']);
        	}else if (data['status'] == 1){
        		console.log(data['msg']);
    			doCheckCamStatus(idCamera);
        	}
        },
        error: function(data,jqXHR,xhr, desc, err) {
            console.log(data);
            console.log(xhr);     
            console.log("Details: " + desc + "\nError:" + err);  
            console.warn('Connection failed');
        }
    }); 
}

// function to check the status of cams in server
function doCheckCamStatus(id_camera) {
	if (id_camera == "camera40") {
		id_camera = "camera1";
	}else if (id_camera == "camera41") {
		id_camera = "camera2";
	}
	var idMembre =  window.localStorage.getItem("id_membre");
	var msg = "";
	var data = {
	        "action": "checkCameraStatus",
	        "id_camera": id_camera,
	        "id_membre": idMembre
	    };
    data = $(this).serialize() + "&" + $.param(data); 
    $.ajax({
        type: 'GET',
        url: 'https://tacks.fr/application/action.php',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 5000,
        data: data,
        cache: true,
        crossDomain: true,
        success: function(data, status){
        	console.log('Check camera status');
        	if (data['status'] == 1){
        		console.log(data['msg']);
        		msg = data['msg'];
        		checkCameraStatus(id_camera, msg);
        		console.log(id_camera + " status: " + data['msg']);
        	}
        },
        error: function(data,jqXHR,xhr, desc, err) {
            console.log(data);
            console.log(xhr);     
            console.log("Details: " + desc + "\nError:" + err);  
            console.warn('Connection failed');
        }
    }); 	
}

// Fonction check Caméra status and set select value
function checkCameraStatus(id_camera, cameStatus) {	
	if (id_camera == "camera1") {
		console.log("Statut check === " + cameStatus);
		if (cameStatus == 1) {
			var option = '<option id="videoStopSelect" value="videoStop" >OFF</option><option id="videoStreamSelect" value="videoStream" selected="selected">ON</option>';
			$("#camera1").empty();
			$("#camera1").append(option);
			$("#camera1").trigger("create"); 
			createImageLayer();
			$("#webcam").css({"display":"inline"});
		}else {
			var option = '<option id="videoStopSelect" value="videoStop" selected="selected">OFF</option><option id="videoStreamSelect" value="videoStream">ON</option>';
			$("#camera1").empty();
			$("#camera1").append(option);
			$("#camera1").trigger("create");
			$("#webcam").css({"display":"none"});
		}
	} else if (id_camera == "camera2") {
		console.log("Statut check === " + cameStatus);
		if (cameStatus == 1) {
			var option = '<option id="videoStopSelect2" value="videoStop" >OFF</option><option id="videoStreamSelect2" value="videoStream" selected="selected">ON</option>';
			$("#camera2").empty();
			$("#camera2").append(option);
			$("#camera2").trigger("create");
			createImageLayerCame2();
			$("#webcamDeux").css({"display":"inline"});
		}else {
			var option = '<option id="videoStopSelect2" value="videoStop" selected="selected">OFF</option><option id="videoStreamSelect2" value="videoStream">ON</option>';
			$("#camera2").empty();
			$("#camera2").append(option);
			$("#camera2").trigger("create");
			$("#webcamDeux").css({"display":"none"});
		}
	}else if (id_camera == "camera3") {
		console.log("Statut check === " + cameStatus);
		if (cameStatus == 1) {
			var option = '<option id="videoStopSelect3" value="videoStop" >OFF</option><option id="videoStreamSelect3" value="videoStream" selected="selected">ON</option>';
			$("#camera3").empty();
			$("#camera3").append(option);
			$("#camera3").trigger("create");
			createImageLayerCame3();
			$("#webcamTrois").css({"display":"inline"});
		}else {
			var option = '<option id="videoStopSelect3" value="videoStop" selected="selected">OFF</option><option id="videoStreamSelect3" value="videoStream">ON</option>';
			$("#camera3").empty();
			$("#camera3").append(option);
			$("#camera3").trigger("create");
			$("#webcamTrois").css({"display":"none"});
		}
	}
}	
// Fonction qui appelle la fonction allumer ou éteindre une caméra
function isCameraStreamOrStop(id_camera) {
	var action = $("#"+id_camera).val();
	videoStreamOrStop(id_camera, action); 

}

function chargeRequestsFunction() {
	doCheckCamStatus('camera1'); 
	doCheckCamStatus('camera2'); 
	doCheckCamStatus('camera3'); 
	createImageLayer(); 
	createImageLayerCame2(); 
	createImageLayerCame3();
}